import { PlusOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Divider, Drawer, message, Modal, Select, Tag } from 'antd';

import React, { useRef, useState } from 'react';
import LockerDetail from './components/LockerDetail';
import RegisterForm from './components/RegisterForm';
import MoteInfoListModal from './components/MoteInfoList/MoteInfoListModal';
import type { DeviceRegisterResponseData, RegisterFormFields, TableListItem } from './data';
import { queryDeviceList, queryLockerDetail, registerDevice, unregisterDevice } from './service';
import { DeviceStatusMap, serviceStatusMapping } from '../utils/utils';
// import { history } from 'umi';

const TableList: React.FC = () => {
  const [currentDevice, setCurrentDevice] = useState<TableListItem>();
  const [detailVisible, setDetailVisible] = useState<boolean>(false);
  const [historyVisible, setHistoryVisible] = useState<boolean>(false);
  const [historyItemId, setHistoryItemId] = useState<string | null>(null);
  const [bindModalVisible, handleBindModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();

  const handleAdd = async (fields: RegisterFormFields) => {
    const hide = message.loading('正在注册');
    try {
      hide();
      const response: DeviceRegisterResponseData = await registerDevice(fields);
      if (response.code === 0) {
        message.success('注册成功');
        handleBindModalVisible(false);
        actionRef.current?.reload();
      } else {
        message.error(response.message);
      }
      return true;
    } catch (error) {
      hide();
      message.error('注册失败请重试！');
      handleBindModalVisible(false);
      return false;
    }
  };

  // const navigationTo = async (deviceNo: string) => {
  //   history.push(`/operation/device/${deviceNo}/warning`);
  // };

  // @ts-ignore
  const columns: ProColumns<TableListItem>[] = [
    {
      title: '设备编号',
      order: 30,
      dataIndex: 'deviceNo',
      render: (_, record) => record.deviceNo,
    },
    {
      title: '设备类型',
      order: 30,
      dataIndex: 'type',
      hideInSearch: true,
      render: (_, record) => {
        if (record.type == 1) {
          return <Tag color={'blue'}>车位锁</Tag>;
        } else if (record.type == 2) {
          return <Tag color={'green'}>地磁</Tag>;
        }
        return '—';
      },
    },
    {
      title: '服务状态',
      order: 20,
      dataIndex: 'serviceStatus',
      valueEnum: () => {
        const map = {};
        serviceStatusMapping.forEach((item) => {
          map[item.key] = {
            text: item.text,
            color: item.color,
            status: item.status,
          };
        });
        return map;
      },
      renderFormItem: () => (
        <Select>
          {serviceStatusMapping
            .filter((item) => item.option)
            .map((item) => (
              <Select.Option key={item.key} value={item.key}>
                {item.text}
              </Select.Option>
            ))}
        </Select>
      ),
    },
    {
      title: '状态',
      order: 28,
      dataIndex: 'status',
      render: (_, record) =>
        record.statusList.map((status) => (
          <Tag color={status?.color} key={status.key}>
            {status?.label}
          </Tag>
        )),
      renderFormItem: () => (
        <Select mode="multiple">
          {DeviceStatusMap.map((item) => (
            <Select.Option key={item.key} value={item.enum.join(',')}>
              {item.label}
            </Select.Option>
          ))}
        </Select>
      ),
    },
    {
      title: '车位号',
      order: 25,
      dataIndex: 'spaceName',
      render: (_, record) => <div>{record.spaceName || '—'}</div>,
    },
    {
      title: '告警次数',
      dataIndex: 'warningCount',
      hideInSearch: true,
      render: (_, record) => (
        // <a onClick={() => navigationTo(record.deviceNo)}>
        <a>
          <Tag color="blue">[{record.warningInfo?.warningCount || 0}]</Tag>
        </a>
      ),
    },
    {
      title: '最近告警时间',
      dataIndex: 'latestWarningTime',
      hideInSearch: true,
      render: (_, record) => <Tag color="green">{record.warningInfo?.latestWarningTime}</Tag>,
    },
    {
      title: '告警内容',
      dataIndex: 'warningContent',
      hideInSearch: true,
      render: (_, record) => <Tag color="green">{record.warningInfo?.warningContent}</Tag>,
    },

    {
      title: '设备电量',
      dataIndex: 'power',
      hideInSearch: true,
      render: (_, record) => (
        <Tag color={record.power ? record.power.color : 'red'}>
          {record.power ? `${record.power.label}` : '未知'}
        </Tag>
      ),
    },
    {
      title: '操作',
      dataIndex: 'option',
      hideInSearch: true,
      render: (_, record) => {
        const onClickDetail = () => {
          setCurrentDevice(record);
          setDetailVisible(true);
        };
        const onClickHistory = () => {
          const { deviceNo } = record;
          setHistoryVisible(true);
          setHistoryItemId(deviceNo);
        };
        const onClickUnRegister = () => {
          const { deviceNo } = record;
          Modal.confirm({
            title: `确定要注销车位锁 ${deviceNo} 吗?`,
            content: (
              <div>
                <Divider />
                <p>注销后无法撤回,清谨慎操作!</p>
              </div>
            ),
            okText: '确定',
            cancelText: '取消',
            onOk: async () => {
              await unregisterDevice({ deviceNo });
              actionRef.current?.reload();
            },
          });
        };

        return (
          <div>
            <a onClick={onClickDetail}>详情</a>
            <Divider type="vertical" />
            <a onClick={onClickHistory}>历史数据</a>
            <Divider type="vertical" />
            <a onClick={onClickUnRegister}>删除</a>
          </div>
        );
      },
    },
  ];

  return (
    <PageHeaderWrapper>
      <ProTable<TableListItem>
        headerTitle="设备列表"
        actionRef={actionRef}
        rowKey="deviceNo"
        toolBarRender={() => [
          <Button type="primary" onClick={() => handleBindModalVisible(true)}>
            <PlusOutlined /> 添加
          </Button>,
        ]}
        tableAlertRender={() => false}
        request={(params = {}) => {
          const { current: page, pageSize, ...filter } = params;
          return queryDeviceList({ page, pageSize, ...filter });
        }}
        columns={columns}
        rowSelection={false}
      />
      {bindModalVisible && (
        <RegisterForm
          values={currentDevice}
          onSubmit={(values: RegisterFormFields) => handleAdd(values)}
          onCancel={() => {
            handleBindModalVisible(false);
            setCurrentDevice(undefined);
          }}
          modalVisible={bindModalVisible}
          visibleHandler={() => handleBindModalVisible(false)}
        />
      )}

      {historyVisible && historyItemId && (
        <MoteInfoListModal
          type="status"
          deviceNo={historyItemId}
          modalVisible={historyVisible}
          onSubmit={() => setHistoryVisible(false)}
          onCancel={() => setHistoryVisible(false)}
        />
      )}

      <Drawer
        visible={!!currentDevice?.deviceNo && detailVisible}
        onClose={() => setDetailVisible(false)}
        width="30%"
      >
        {!!currentDevice?.deviceNo && detailVisible && (
          <LockerDetail
            deviceNo={currentDevice?.deviceNo}
            request={(id) => queryLockerDetail({ deviceNo: id })}
          />
        )}
      </Drawer>
    </PageHeaderWrapper>
  );
};

export default TableList;
